Angular Lifecycle Hooks

Key moments-ல் Angular call செய்யும் methods-ஐ கற்றுக்கொள்ளுங்கள் (create, input changes, view init, destroy)

Angular Lifecycle Hooks

Lifecycle hooks என்பது key moments-ல் Angular call செய்யும் methods ஆகும் (init, input changes, view init, destroy) அதனால் நீங்கள் set up, changes-கு react, template refs access, மற்றும் clean up செய்யலாம்.

Lifecycle Essentials

  • What: Lifecycle hooks என்பது key moments-ல் Angular call செய்யும் methods ஆகும் (init, input changes, view init, destroy).
  • Setup: Inputs set ஆகிய பிறகு ngOnInit பயன்படுத்தவும்.
  • React: Input changes handle செய்ய ngOnChanges-ல்.
  • DOM ready: @ViewChild refs access செய்ய ngAfterViewInit பயன்படுத்தவும்.
  • Cleanup: Timers/subscriptions/listeners release செய்ய ngOnDestroy-ல்.

Lifecycle Hooks Example

import { OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

export class Demo implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('box') box!: ElementRef<HTMLInputElement>;
  intervalId: any;
  ngOnInit() { /* setup after inputs */ }
  ngAfterViewInit() { this.box.nativeElement.focus(); }
  ngOnDestroy() { clearInterval(this.intervalId); }
}

// Template: <input #box>

Example Explained

  • ngOnInit: Inputs already bound ஆகிய பிறகு setup run செய்ய.
  • @ViewChild + ngAfterViewInit: View initialized ஆகிய பிறகு input-ஐ access மற்றும் focus செய்ய.
  • ngOnDestroy: Leaks prevent செய்ய timers/listeners clean up செய்ய.

Notes

  • Related: Views create செய்ய Components, markup மற்றும் refs-க்கு Templates, மற்றும் examples-ல் பயன்படுத்தப்படும் *ngIf போன்ற structural rendering-க்கு Directives ஆகியவற்றை காணவும்.
  • Avoid DOM access in constructors.

Lifecycle Hooks

Lifecycle toggle: ஒரு component show செய்தல் (e.g., *ngIf உடன்) ngOnInit run செய்கிறது; hide செய்தல் ngOnDestroy run செய்கிறது.

Work do/undo: Init-ல் timers/subscriptions start செய்யவும், destroy-ல் clear/unsubscribe செய்யவும்.

Lifecycle Hooks Syntax

export class Child implements OnInit, OnDestroy {
  intervalId: any;
  ngOnInit() { this.intervalId = setInterval(() => {/* ... */}, 1000); }
  ngOnDestroy() { clearInterval(this.intervalId); }
  // <child-cmp *ngIf="show"></child-cmp>

Example

Lifecycle Hooks Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'child-cmp',
  standalone: true,
  template: `<p>Child works!</p>`
})
export class Child implements OnInit, OnDestroy {
  intervalId: any;
  ngOnInit() {
    console.log('Child: ngOnInit');
    this.intervalId = setInterval(() => console.log('Child: tick'), 1000);
  }
  ngOnDestroy() {
    console.log('Child: ngOnDestroy');
    clearInterval(this.intervalId);
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, Child],
  template: `
    <h3>Lifecycle Hooks</h3>
    <button (click)="toggle()">Toggle Child</button>
    <child-cmp *ngIf="show"></child-cmp>
  `
})
export class App {
  show = true;
  toggle() { this.show = !this.show; }
}

bootstrapApplication(App);

Example Explained

  • Toggle: Button show flip செய்கிறது child add/remove செய்ய.
  • Hooks in action: Child create செய்தல் ngOnInit run செய்கிறது; remove செய்தல் ngOnDestroy run செய்கிறது.
  • Cleanup: Interval clear செய்தல் destroy-க்கு பிறகு background work prevent செய்கிறது.

Notes

  • Cleanup required: Intervals/timeouts clear செய்யவும் மற்றும் ngOnDestroy-ல் unsubscribe செய்யவும்; possible ஆக இருக்கும் போது async pipe பயன்படுத்தவும்.
  • Heavy work in hooks: Frequently called hooks-ல் expensive work avoid செய்யவும் (e.g., ngOnChanges); debounce/throttle செய்யவும் அல்லது services-க்கு defer செய்யவும்.
  • Manual listeners: நீங்கள் manually add செய்யும் event listeners destroy-ல் remove செய்யவும், அல்லது Renderer2 return செய்யும் cleanup function வைக்கவும்.

OnChanges Example

Parent → Child: Input box parent-ல் text update செய்கிறது; child [text] மூலம் அதை receive செய்கிறது.

Change record: Child SimpleChanges-லிருந்து last prev மற்றும் curr values store செய்கிறது display-க்கு.

Edge cases: undefined → value அல்லது value → '' போன்ற transitions handle செய்கிறது.

OnChanges Example Code

import { bootstrapApplication } from '@angular/platform-browser';
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'child-cmp',
  standalone: true,
  template: `
    <p>Child: {{ text }}</p>
    <p *ngIf="lastChange">Last change: {{ lastChange.prev }} → {{ lastChange.curr }}</p>
  `
})
export class Child implements OnChanges {
  @Input() text = '';
  lastChange: { prev: any; curr: any } | null = null;
  ngOnChanges(changes: SimpleChanges) {
    if (changes['text']) {
      this.lastChange = {
        prev: changes['text'].previousValue,
        curr: changes['text'].currentValue
      };
    }
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, Child],
  template: `
    <h3>ngOnChanges</h3>
    <input [(ngModel)]="text" placeholder="Type to see changes">
    <child-cmp [text]="text"></child-cmp>
  `
})
export class App {
  text = '';
}

bootstrapApplication(App);

Example Explained

  • @Input(): Child text என்று input declare செய்கிறது parents bind செய்ய முடியும்.
  • ngOnChanges(changes): Changed input-க்கு previousValue மற்றும் currentValue கொண்ட SimpleChanges receive செய்கிறது.
  • Immutable updates: Change detection trigger செய்ய in place mutate செய்வதை விட references replace செய்ய விரும்பவும்.

Notes

  • Immutable inputs: OnChanges run செய்ய arrays/objects replace செய்யவும் mutate செய்வதை விட.
  • With OnPush: Input reference changes checks trigger செய்கின்றன; in-place mutation செய்யாது—parents-லிருந்து new references emit செய்யவும்.
  • Inspect changes: Edge cases handle செய்ய SimpleChanges பயன்படுத்தவும் (e.g., undefined → value).

AfterViewInit Example

Multiple refs: @ViewChild மூலம் input box மற்றும் panel container இரண்டையும் read செய்கிறது.

Defer DOM work: View settle ஆக அனுமதிக்க ngAfterViewInit-ல் setTimeout பயன்படுத்துகிறது measuring-க்கு முன்.

measure(): Bounding box read செய்து size string format செய்கிறது.

AfterViewInit Example

import { bootstrapApplication } from '@angular/platform-browser';
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <h3>ngAfterViewInit</h3>
    <input #box placeholder="I will be focused">
    <div #panel style="width:200px;height:100px;background:#f0f0f0;margin-top:8px;">
      Panel
    </div>
    <p>Panel size: {{ size }}</p>
  `
})
export class App implements AfterViewInit {
  @ViewChild('box') box!: ElementRef<HTMLInputElement>;
  @ViewChild('panel') panel!: ElementRef<HTMLDivElement>;
  size = '';

  ngAfterViewInit() {
    // Focus the input
    this.box.nativeElement.focus();
    
    // Let view settle then measure
    setTimeout(() => this.measure(), 0);
  }

  measure() {
    const rect = this.panel.nativeElement.getBoundingClientRect();
    this.size = `${Math.round(rect.width)}×${Math.round(rect.height)} px`;
  }
}

bootstrapApplication(App);

Example Explained

  • @ViewChild('box') box!: ElementRef<HTMLInputElement>;: Input box-க்கு reference declare செய்கிறது.
  • ngAfterViewInit() { this.box.nativeElement.focus(); }: View initialized ஆகிய பிறகு focus செய்கிறது.
  • Immutable inputs: Change detection trigger செய்ய in place mutate செய்வதை விட references replace செய்ய விரும்பவும்.

Notes

  • Don't use DOM in constructor: View ready இல்லை; DOM operations ngAfterViewInit-க்கு பிறகு செய்யவும்.
  • Reading too early: @ViewChild ngAfterViewInit-க்கு முன் undefined—existence check செய்யவும் அல்லது work defer செய்யவும்.

AfterViewInit & Cleanup

View initializes ஆகிய பிறகு template refs access செய்யவும் மற்றும் component destroy ஆகும் போது resources clean up செய்யவும்.

Cleanup Pattern

// Example teardown pattern
sub?.unsubscribe?.();
clearInterval(intervalId);
removeListener?.();

Example Explained

  • Teardown: ngOnDestroy-ல் unsubscribe, intervals clear, மற்றும் listeners remove செய்யவும்.
  • Safety: Optional chaining (?.) missing handles-க்கு guard செய்கிறது.

Notes

  • Focus and measure safely: DOM reads/writes ngAfterViewInit-க்கு பிறகு run செய்யவும் (அல்லது view settle ஆக அனுமதிக்க setTimeout-ல்).
  • Observers & listeners: ResizeObserver/MutationObserver disconnect செய்யவும் மற்றும் manual event listeners remove செய்யவும் ngOnDestroy-ல்.
  • Subscriptions: Async pipe பயன்படுத்தவும்; நீங்கள் manually subscribe செய்யும் போது, destroy-ல் unsubscribe செய்யவும் (e.g., takeUntilDestroyed).

Exercise

Which lifecycle hook runs after the component's view has been fully initialized?

ngOnInit
✗ Incorrect! ngOnInit component initialize ஆகிய பிறகு run செய்கிறது, view fully initialized-க்கு அல்ல
ngAfterViewInit
✓ Correct! ngAfterViewInit component-ன் view fully initialized ஆகிய பிறகு run செய்கிறது
ngOnDestroy
✗ Incorrect! ngOnDestroy component destroy ஆகும் போது run செய்கிறது, view initialization-க்கு அல்ல
அடுத்தது